package com.example.demo.excel.web;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.example.demo.annotation.ApiDesc;
import com.example.demo.entity.base.ResponseEntity;
import com.example.demo.entity.excel.UserExcelModel;
import com.example.demo.excel.service.ExcelModelService;

@RestController
@RequestMapping(value = "/excelmodel")
public class ExcelModelController {
	
	@Autowired
	private ExcelModelService excelModelService;
	
	@ApiDesc("导入用户信息")
	@PostMapping(value = "/importusers")
	public Object importUsers(HttpServletRequest request,@RequestParam("excelFile") MultipartFile excelFile) throws IOException {
		
		ResponseEntity<Map<String, String>> ret = excelModelService.importUsers(excelFile);
		
		return ret;	
	}
	
	@ApiDesc("下载用户导入模板")
	@RequestMapping(value = "/downloadusermodel")
	public void downloadUserModel (HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		String fileName = URLEncoder.encode("用户导入模板", "UTF-8").replaceAll("\\+", "%20");
		
		outputExcel(response, fileName, UserExcelModel.class);
	}

	/**
	 * 
	 * @方法名 ExcelModelController.java
	 * @创建者 xzw
	 * @创建日期 2022年1月4日
	 * @返回类型 void
	 * @功能描述 输出excel模板到客户端
	 *
	 */
	private void outputExcel(HttpServletResponse response, String fileName, Class head)
			throws IOException {
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(),head).sheet("模板").doWrite(new ArrayList<>());
	}
}
